<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">学校管理</text>
    </view>
    
    <!-- 搜索和添加区域 -->
    <view class="search-box">
      <view class="search-input">
        <input type="text" v-model="keyword" placeholder="请输入学校名称搜索" />
        <button class="search-btn" @tap="handleSearch">搜索</button>
      </view>
      <button class="add-btn" @tap="handleAdd">添加学校</button>
    </view>
    
    <!-- 学校列表 -->
    <view class="school-list" v-if="schoolList.length > 0">
      <view 
        class="school-item" 
        v-for="(item, index) in schoolList" 
        :key="item._id"
      >
        <view class="school-info">
          <view class="school-name">{{item.name}}</view>
          <view class="school-code">代码: {{item.code}}</view>
          <view class="school-detail">
            <text>地区: {{item.region}}</text>
            <text class="school-level">等级: {{item.level}}</text>
          </view>
        </view>
        <view class="school-actions">
          <button class="edit-btn" @tap="handleEdit(item)">编辑</button>
          <button class="delete-btn" @tap="handleDelete(item._id)">删除</button>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text>暂无学校数据</text>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading" v-if="isLoading">
      <text>加载中...</text>
    </view>
    
    <!-- 分页区域 -->
    <view class="pagination" v-if="schoolList.length > 0">
      <button 
        class="prev-btn" 
        :disabled="currentPage <= 1"
        @tap="handlePrevPage"
      >上一页</button>
      <text class="page-info">第 {{currentPage}} 页</text>
      <button 
        class="next-btn" 
        :disabled="schoolList.length < pageSize"
        @tap="handleNextPage"
      >下一页</button>
    </view>
    
    <!-- 添加/编辑学校弹窗 -->
    <view class="popup" v-if="showPopup">
      <view class="popup-mask" @tap="showPopup = false"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{isEdit ? '编辑学校' : '添加学校'}}</text>
          <text class="popup-close" @tap="showPopup = false">×</text>
        </view>
        <view class="popup-form">
          <view class="form-item">
            <text class="form-label">学校名称:</text>
            <input class="form-input" type="text" v-model="formData.name" placeholder="请输入学校名称" />
          </view>
          <view class="form-item">
            <text class="form-label">学校代码:</text>
            <input class="form-input" type="text" v-model="formData.code" placeholder="请输入学校代码" />
          </view>
          <view class="form-item">
            <text class="form-label">所在地区:</text>
            <input class="form-input" type="text" v-model="formData.region" placeholder="请输入所在地区" />
          </view>
          <view class="form-item">
            <text class="form-label">学校等级:</text>
            <picker class="form-picker" mode="selector" :range="levelOptions" :value="levelIndex" @change="handleLevelChange">
              <view class="picker-content">
                {{ formData.level || '请选择学校等级' }}
              </view>
            </picker>
          </view>
          <view class="form-actions">
            <button class="cancel-btn" @tap="showPopup = false">取消</button>
            <button class="confirm-btn" @tap="handleSubmit">确定</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'

// 数据列表
const schoolList = ref([])
const isLoading = ref(false)
const keyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗相关
const showPopup = ref(false)
const isEdit = ref(false)
const currentId = ref('')
const formData = reactive({
  name: '',
  code: '',
  region: '',
  level: ''
})

// 学校等级选项
const levelOptions = ['985', '211', '双一流', '普通高校']
const levelIndex = computed(() => {
  return levelOptions.indexOf(formData.level)
})

// 获取学校列表
const getSchoolList = async () => {
  isLoading.value = true
  try {
    const res = await uniCloud.callFunction({
      name: 'get_schools',
      data: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: keyword.value
      }
    })
    
    if (res.result.code === 0) {
      schoolList.value = res.result.data
    } else {
      uni.showToast({
        title: res.result.message || '获取学校列表失败',
        icon: 'none'
      })
    }
  } catch (e) {
    console.error('获取学校列表异常', e)
    uni.showToast({
      title: '获取学校列表异常',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 添加学校按钮点击
const handleAdd = () => {
  isEdit.value = false
  currentId.value = ''
  formData.name = ''
  formData.code = ''
  formData.region = ''
  formData.level = ''
  showPopup.value = true
}

// 编辑学校按钮点击
const handleEdit = (school) => {
  isEdit.value = true
  currentId.value = school._id
  formData.name = school.name
  formData.code = school.code
  formData.region = school.region || ''
  formData.level = school.level || ''
  showPopup.value = true
}

// 删除学校
const handleDelete = (id) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该学校吗？',
    success: async (res) => {
      if (res.confirm) {
        isLoading.value = true
        try {
          const res = await uniCloud.callFunction({
            name: 'manage_school',
            data: {
              action: 'delete',
              id
            }
          })
          
          if (res.result.code === 0) {
            uni.showToast({
              title: '删除成功'
            })
            getSchoolList()
          } else {
            uni.showToast({
              title: res.result.message || '删除失败',
              icon: 'none'
            })
          }
        } catch (e) {
          console.error('删除学校异常', e)
          uni.showToast({
            title: '删除学校异常',
            icon: 'none'
          })
        } finally {
          isLoading.value = false
        }
      }
    }
  })
}

// 表单提交
const handleSubmit = async () => {
  // 表单验证
  if (!formData.name) {
    uni.showToast({
      title: '请输入学校名称',
      icon: 'none'
    })
    return
  }
  
  if (!formData.code) {
    uni.showToast({
      title: '请输入学校代码',
      icon: 'none'
    })
    return
  }
  
  isLoading.value = true
  try {
    const res = await uniCloud.callFunction({
      name: 'manage_school',
      data: {
        action: isEdit.value ? 'update' : 'add',
        id: currentId.value,
        school: {
          name: formData.name,
          code: formData.code,
          region: formData.region,
          level: formData.level
        }
      }
    })
    
    if (res.result.code === 0) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '添加成功'
      })
      showPopup.value = false
      getSchoolList()
    } else {
      uni.showToast({
        title: res.result.message || (isEdit.value ? '更新失败' : '添加失败'),
        icon: 'none'
      })
    }
  } catch (e) {
    console.error('提交数据异常', e)
    uni.showToast({
      title: '提交数据异常',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 学校等级选择
const handleLevelChange = (e) => {
  const index = e.detail.value
  formData.level = levelOptions[index]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getSchoolList()
}

// 上一页
const handlePrevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    getSchoolList()
  }
}

// 下一页
const handleNextPage = () => {
  if (schoolList.value.length === pageSize.value) {
    currentPage.value++
    getSchoolList()
  }
}

// 页面加载
onMounted(() => {
  getSchoolList()
})
</script>

<style>
.container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.search-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  display: flex;
  flex: 1;
  margin-right: 10px;
}

.search-input input {
  flex: 1;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
}

.search-btn {
  width: 80px;
  height: 40px;
  line-height: 40px;
  margin-left: 10px;
  background-color: #007AFF;
  color: white;
  font-size: 14px;
  text-align: center;
}

.add-btn {
  width: 120px;
  height: 40px;
  line-height: 40px;
  background-color: #07C160;
  color: white;
  font-size: 14px;
  text-align: center;
}

.school-list {
  margin-bottom: 20px;
}

.school-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.school-info {
  flex: 1;
}

.school-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.school-code {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.school-detail {
  display: flex;
  font-size: 12px;
  color: #999;
}

.school-level {
  margin-left: 20px;
}

.school-actions {
  display: flex;
  flex-direction: row;
}

.edit-btn, .delete-btn {
  width: 60px;
  height: 30px;
  line-height: 30px;
  font-size: 12px;
  text-align: center;
  margin-left: 10px;
}

.edit-btn {
  background-color: #007AFF;
  color: white;
}

.delete-btn {
  background-color: #FF3B30;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.loading {
  text-align: center;
  padding: 20px 0;
  color: #666;
}

.pagination {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.prev-btn, .next-btn {
  width: 80px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  text-align: center;
}

.page-info {
  margin: 0 20px;
  color: #666;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
}

.popup-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.popup-title {
  font-size: 16px;
  font-weight: bold;
}

.popup-close {
  font-size: 24px;
  color: #999;
}

.popup-form {
  padding: 15px;
}

.form-item {
  margin-bottom: 15px;
}

.form-label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}

.form-input, .form-picker {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 10px;
}

.picker-content {
  height: 40px;
  line-height: 40px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn, .confirm-btn {
  width: 80px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  text-align: center;
  margin-left: 10px;
}

.cancel-btn {
  background-color: #F2F2F2;
  color: #333;
}

.confirm-btn {
  background-color: #07C160;
  color: white;
}
</style> 